<?php

namespace app\modules\admin\controllers;

use app\modules\admin\models\User;
use app\modules\admin\models\Article;
use yii\helpers\Url;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\data\Pagination;

/**
 * Default controller for the `admin` module
 */
class IndexController extends Controller
{
    public $layout = "admin";

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function ($rule, $action) {
                    $this->redirect(['login/index']);//游客返回登录页面
                },
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => [''],
                        'roles' => ['?'],//？代表游客
                    ],
                    [
                        'allow' => true,//不写action就默认表示允许所有方法
                        'roles' => ['@'],//@代表已登录用户
                    ],
                ],
            ]
        ];
    }

    /**
     * 后台首页
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 修改密码
     *
     * @return string
     */
    public function actionChangepwd()
    {
//        echo \Yii::$app->user->identity->password;
//        dd(\Yii::$app->request->post('oldpwd'));
        $request = \Yii::$app->request;
        $oldpwd = $request->post('oldpwd');
        $newpwd = $request->post('newpwd');
        if (\Yii::$app->getSecurity()->validatePassword($oldpwd, \Yii::$app->user->identity->password)) {
            $id = \Yii::$app->user->identity->id;
            $admin = User::findOne($id);
            $admin->password = \Yii::$app->getSecurity()->generatePasswordHash($newpwd);
            $res = $admin->save();
            if ($res) {
                \Yii::$app->user->logout();
                return json_encode(['status' => 1, 'redirect' => Url::toRoute(['login/index'])]);
            } else {
                return json_encode(['status' => 0, 'error' => '修改失败，请稍后再试']);
            }
        } else {
            return json_encode(['status' => 0, 'error' => '旧密码错误,请重新输入']);
        }
    }

    /**
     * 文章列表
     *
     * @return mixed
     */
    public function actionArticleList()
    {
        $cate_id = intval(\Yii::$app->request->get('cate_id'));//装换成整形，可以有效的防止xss注入
        $article = new Article();
        $query = $article->find()->where(['cate_id' => $cate_id]);
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count,'defaultPageSize'=>'5',]);
        $art = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        $con = $pagination->offset;
        return $this->render("article_list", [
            'article' => $art,
            'con' => $con,
            'pagination' => $pagination,
        ]);
    }
}